// store/permission.js
import { asyncRoutes, constantRoutes } from '@/router';

function hasPermission(roles, route) {
    if (route.meta && route.meta.role) {
        return roles.some(roles => route.meta.roles.indexOf(roles) >= 0)
    } else {
        return true
    }
}

const storePermission = {
    namespaced: true,
    state: {
        routers: constantRoutes,
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers;
            state.routers = constantRoutes.concat(routers);
        }
    },
    actions: {
        // GenerateRoutes({ commit }, data) {
        //     return new Promise(resolve => {
        //         console.log(data)
        //         const { roles } = data;
        //         roles.push(3)
        //         console.log(roles);
        //         const accessedRouters = asyncRoutes.filter(v => {
        //             if (roles.indexOf('3') >= 0) return true;
        //             if (hasPermission(roles, v)) {
        //                 if (v.children && v.children.length > 0) {
        //                     v.children = v.children.filter(child => {
        //                         if (hasPermission(roles, child)) {
        //                             return child
        //                         }
        //                         return false;
        //                     });
        //                     return v
        //                 } else {
        //                     return v
        //                 }
        //             }
        //             return false;
        //         });
        //         commit('SET_ROUTERS', accessedRouters);
        //         resolve();
        //     })
        // }

        GenerateRoutes({ commit }, roles) {
            return new Promise(resolve => {
                let accessedRoutes
                console.log(roles)
                // if (roles[0] === 3) {
                accessedRoutes = asyncRoutes || []
                // } else {
                accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
                // }
                // console.log(accessedRoutes)
                commit('SET_ROUTERS', accessedRoutes)
                resolve(accessedRoutes)
            })
        }
    }
};

export const filterAsyncRoutes = (routes, roles) => {
    const res = [];
    routes.forEach(route => {
        let temp = { ...route };
        if (hasPermission(roles, temp)) {
            if (temp.children) {
                temp.children = filterAsyncRoutes(temp.children, roles)
            }
            res.push(temp)
        }
    })
    return res;
}


export default storePermission;